let app = getApp();

Page({
  data: {
    isLogin: false, // 控制是否登录
    userInfo: [],
    isOpen: false, // 接单开关状态
    tableList: [],
    todayOrders: 0, // 新增：今日订单数
    totalOrders: 0, // 新增：累计订单数
    todayAmount: 0.00, // 新增：今日金额
    totalAmount: 0.00, // 新增：累计金额
    waitTotalAmount: 0.00, // 等待结算总金额
    money: 0 //提现金额初始值
  },
  showModalDialog: function () {
    wx.showModal({
      title: '提示',
      editable: true,
      placeholderText: '请输入提现金额',
      success: function (res) {
        if (res.confirm) {
          let inputContent = res.content;
          console.log('提现金额：', inputContent);
          if (!isNaN(inputContent) && parseFloat(inputContent) > 0) {
            const moneyAmount = parseFloat(inputContent);
            if (moneyAmount > this.data.totalAmount - this.data.userInfo.money) {
              wx.showToast({
                title: '金额不足',
                icon: 'none'
              });
              return;
            } else {
              this.setData({
                money: this.data.money + moneyAmount, // 累加提现中的金额
                totalAmount: this.data.totalAmount // 从待提现金额中减去相应数额
              }, () => {
                console.log('新的提现中金额:', this.data.money);
                console.log('新的待提现金额:', this.data.totalAmount);
                this.submitWithdrawal(moneyAmount);
              });
            }
          } else {
            wx.showToast({
              title: '请输入有效的提现金额',
              icon: 'none'
            });
          }
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }.bind(this)
    });
  },
  submitWithdrawal: function (pay) {
    let id = app.globalData.userID;
    wx.request({
      url: 'http://localhost:8080/master/master/updateMasterMoney',
      method: "PUT",
      data: JSON.stringify({
        id: id,
        money: pay,
        waitTotalAmount: this.data.waitTotalAmount
      }),
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log("提现请求成功", res);
        if (res.data.code === 200) {
          wx.showToast({
            title: '提现申请提交成功',
            icon: 'success',
            duration: 1500

          });
          this.getData();
        } else {
          wx.showToast({
            title: '提现申请提交失败，请重试',
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: (err) => {
        console.error("提现请求失败", err);
        wx.showToast({
          title: '提现申请提交失败，请重试',
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  onLoad() {
    this.getData();
    let temp = wx.getStorageSync('app.globalData.userID');
    console.log(temp);
    let id = app.globalData.userID;
    console.log("师傅id:" + id);
    this.setData({
      "money": storedmoney
    });
  },

  onShow() {
    this.checkLoginStatus();
    this.getData();
  },

  getData() {
    let id = app.globalData.userID;
    wx.request({
      url: 'http://localhost:8080/master/master/' + id,
      method: "GET",
      success: (res) => {
        console.log(res);
        this.setData({
          userInfo: res.data.data,
        });
        wx.request({
          url: 'http://localhost:8080/usermy/order/list?masterId=' + id,
          method: "GET",
          success: (res) => {
            console.log(res.data.rows);
            let totalEndMoney = 0; // 初始化总金额为0
            let todayEndMoney = 0; // 初始化今日金额为0
            let totalOrdersCount = 0; // 累计订单数
            let todayOrdersCount = 0; // 今日订单数
            let waitTotalEndMoney = 0;
            let orderInfo = res.data.rows;

            // 当天日期
            let today = new Date().toISOString().split('T')[0];
            for (let i = 0; i < orderInfo.length; i++) {
              if (orderInfo[i].orderStatus == 2) {
                totalEndMoney += (orderInfo[i].endMoney + orderInfo[i].serviceTable.prepayment);
                totalOrdersCount++;
                // 计算今日订单和金额
                if (orderInfo[i].creationTime.split(' ')[0] === today) {
                  todayEndMoney += (orderInfo[i].endMoney + orderInfo[i].serviceTable.prepayment);
                  todayOrdersCount++;
                }
              }
              if (orderInfo[i].orderStatus == 1) {
                waitTotalEndMoney += (orderInfo[i].endMoney + orderInfo[i].serviceTable.prepayment);
              }

            }
            this.setData({
              orderInfo: orderInfo,
              endMoney: totalEndMoney,
              todayAmount: todayEndMoney,
              totalAmount: totalEndMoney,
              todayOrders: todayOrdersCount,
              totalOrders: totalOrdersCount,
              waitTotalAmount: waitTotalEndMoney
            });
          },
          fail: (err) => {
            console.error("请求失败", err);
          }
        });
      },
      fail: (err) => {
        console.error("请求失败", err);
      }
    });
  },
  // 检查登录状态
  checkLoginStatus() {
    this.setData({
      isLogin: app.globalData.isLogin
    });
    wx.setStorageSync('isLogin', app.globalData.isLogin);
  },

  // 直接登录
  goToLogin() {
    wx.navigateTo({
      url: '/packageMy/pages/login/login'
    });
  },

  // 切换接单状态
  switchChange(e) {
    this.setData({
      isOpen: e.detail.value,
    });
    if (!this.data.isOpen) {
      wx.showModal({
        title: '提示',
        content: '确定要下线吗？',
        success: (res) => {
          if (res.confirm) {
            this.setData({
              isOpen: false,
            });
            wx.showToast({
              title: '已下线',
              icon: 'success',
              duration: 1500
            });
          } else if (res.cancel) {
            this.setData({
              isOpen: true
            });
          }
        }
      });
    }
  },

  // 显示结算规则提示
  showTip() {
    wx.showModal({
      title: '结算规则',
      content: '师傅完成后7天自动结算,用户完成评价后自动结算',
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.globalData.isLogin = false;
          this.setData({
            isLogin: app.globalData.isLogin
          });
          // 显示退出成功提示
          wx.showToast({
            title: '已退出登录',
            icon: 'success',
            duration: 1500
          });
        }
      }
    });
  }
});